package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Transactional
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    private String prefix; //所有文件在OSS桶里面的顶层目录

    @Value("${file.oss.web-site}")
    private String webSite; //OSS中素材的域名

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.判断参数合法性
        if(multipartFile==null || multipartFile.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.设置文件名为唯一
        String prefixFileName = UUID.randomUUID().toString().replace("-",""); //使用UUID生成文件名前缀
        String originalFilename = multipartFile.getOriginalFilename(); //获取上传文件的原始文件名，文件名格式如： 1.2.a.b.c.png
        int lastIndex = originalFilename.lastIndexOf(".");//获取最后一个.的索引位置
        String postFileName = originalFilename.substring(lastIndex); //获取文件后缀名

        String fullFileName = prefixFileName + postFileName; //上传的OSS的文件的完整文件名（唯一的）

        //4.调用OSS的上传，获取相对路径
        String url = null;
        try {
            url = fileStorageService.store(prefix, fullFileName, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR, "上传出现问题");
        }

        WmMaterial wmMaterial = new WmMaterial();
        if(StringUtils.isNotBlank(url)){
            //5.构建素材实例并保存素材

            wmMaterial.setUserId(wmUser.getId()); //用户ID
            wmMaterial.setUrl(url);//文件相对路径
            wmMaterial.setType((short)0); //0-图片
            wmMaterial.setIsCollection((short)0); //0-未收藏
            wmMaterial.setCreatedTime(new Date());

            save(wmMaterial);
        }

        //6.为素材的URL添加域名
        wmMaterial.setUrl(webSite + url);


        //清理threaLocal
        WmThreadLocalUtils.clear();

        //7.响应素材
        return ResponseResult.okResult(wmMaterial);
    }


    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //1.判断参数是否为空
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.检查分页参数设置默认值
        dto.checkParam();

        //3.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();

        //4.根据isCollection判断如果有值拼接查询条件
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(dto.getIsCollection()>0){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        //5.设置固定查询条件（当前用户ID） 和 按照创建时间倒排
        lambdaQueryWrapper.eq(WmMaterial::getUserId, wmUser.getId());
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //6.执行分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        this.page(page,lambdaQueryWrapper);

        //7.遍历列表中的素材，为每个素材添加域名
        List<WmMaterial> wmMaterialList = page.getRecords();
        wmMaterialList.forEach(x -> {
            x.setUrl(webSite + x.getUrl());
        });

        //8.封装分页响应结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),(int)page.getTotal());
        responseResult.setData(wmMaterialList);


        //清理threaLocal
        WmThreadLocalUtils.clear();

        //9.响应数据
        return responseResult;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;


    @Override
    public ResponseResult del(Integer id) {
        //1.判断参数合法性
        if(id==null ||id==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.查询素材并判断是否存在
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "素材不存在无法删除");
        }

        //4.判断素材是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if(count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR, "素材被引用，不能删除");
        }

        //5.根据ID删除素材
        removeById(id);

        //6.删除OSS中的素材
        fileStorageService.delete(wmMaterial.getUrl());


        //清理threaLocal
        WmThreadLocalUtils.clear();

        //7.响应数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Override
    public ResponseResult collect(Integer id, Short isCollect) {
        //1.判断参数合法性
        if(id==null ||id==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.查询素材并判断是否存在
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "素材不存在无法删除");
        }


        //4.通过ID更新素材的是否收藏字段
        WmMaterial wmMaterialDB = new WmMaterial();
        wmMaterialDB.setId(id);
        wmMaterialDB.setIsCollection(isCollect);
        updateById(wmMaterialDB);


        //清理threaLocal
        WmThreadLocalUtils.clear();


        //5.响应数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
